﻿using System;
using System.Web;
using System.Text;
using System.Web.Caching;

namespace SelArom.Net.Sitefinity.HttpHandlers
{
	/// <summary>
	/// HttpHandler for creating a simple site navigation menu from the Sitefinity SiteMap
	/// </summary>
	public class SmoothMenuSource : IHttpHandler
	{
		private const string top = "<html><head /><body><div id=\"smoothmenu\" class=\"smoothmenu\"><ul class=\"menu\">";
		private const string bottom = "</ul></div></body></html>";

		public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentType = "text/html";
			context.Response.Clear();
			context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

			var sb = new StringBuilder();
			sb.Append(top);
			var count = 0;

			var referral = context.Request.UrlReferrer;
			var url = referral == null ? new string[0] : context.Request.UrlReferrer.LocalPath.Split('/');

			foreach (SiteMapNode node in System.Web.SiteMap.RootNode.ChildNodes)
			{
				// first and last css class for root
				var css = string.Empty;
				if (count == 0)
					css = " class=\"first\"";
				else if (count == System.Web.SiteMap.RootNode.ChildNodes.Count - 1)
					css = " class=\"last\"";

				// determine site section
				var selected = string.Empty;

				if (url.Length > 1)
				{
					var curUrl = url[1].ToLower();

					var secUrls = node.Url.Split('/');
					if (secUrls.Length > 1)
					{
						var secUrl = secUrls[1].ToLower();
						selected = secUrl == curUrl ? "selected" : string.Empty;
					}
				}

				// append root menu node
				sb.AppendFormat("<li{2}><a href=\"{0}\" class=\"{3}\">{1}</a>", node.Url.Replace("~", ""), node, css, selected);

				// append children (1 level deep only for now)
				if (node.HasChildNodes)
				{
					sb.Append("<ul>");
					foreach (SiteMapNode subnode in node.ChildNodes)
						sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", subnode.Url.Replace("~", ""), subnode);
					sb.Append("</ul>");
				}

				// close root menu node
				sb.Append("</li>");
				count++;
			}
			sb.Append(bottom);


			// TODO: reimplement caching while supporting "selected" top-menu state
			context.Response.Write(sb.ToString());
			context.Response.Flush();
			context.Response.End();
		}

		public bool IsReusable
		{
			get { return false; }
		}
	}
}